package com.baizhi.basic;/*
2023/7/18
    */

import com.baizhi.common.exception.IllUsernameOrPwdException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    //系统出现异常了会默认执行该方法，没有异常的时候该方法不会执行
    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //告知浏览器我们响应的是一个json串
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setCharacterEncoding("UTF-8");
        //把异常捕捉到，把异常信息封装响应里面。传给前端。
        e.printStackTrace();
        if(e instanceof IllUsernameOrPwdException) {
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        }else{
            httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("msg",e.getMessage());
        //把resultMap转换为json串传给response
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(httpServletResponse.getWriter(),resultMap);
        return new ModelAndView();
    }
}
